package com.modules.service.sys.impl;


import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.util.AES2;
import com.common.util.AesMin;
import com.common.util.ConstantUtil;
import com.common.util.MyDateUtil;
import com.common.vo.LoginUser;
import com.common.vo.Result;
import com.modules.dao.sys.UserDao;
import com.modules.dto.sys.resp.UserEntityResp;
import com.modules.entity.sys.UserEntity;
import com.modules.service.sys.UserService;

import cn.hutool.core.util.StrUtil;

/**
 * service用户
 *
 * @author yyq
 */
@Service
public class UserServiceImp extends ServiceImpl<UserDao, UserEntity> implements UserService{

    private final Logger logger = Logger.getLogger(UserServiceImp.class);

    @Autowired
    private UserDao dao;
    @Autowired
    private HttpSession session;


    /**
     * 查询
     * @return
     */
    public Result<?> select(Page<UserEntity> page, UserEntity user) {
    	user.setDelFlag(ConstantUtil.NOT_DEL);
        IPage<UserEntityResp> iPage = dao.getPage(page, user);
        return Result.success(iPage.getRecords(), iPage.getTotal());
    }

    /**
     * 插入
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> insert(UserEntity user) {
    	return insertOrupdate(user);
    }
    
    /**
     * 更新
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update(UserEntity user) {
    	return insertOrupdate(user);
    }
    
    public Result<?> insertOrupdate(UserEntity user){
    	user.setDelFlag(ConstantUtil.NOT_DEL);
    	user.setOid(1);// 需要分组织则oid改为界面获取
    	user.setLastOid(1);
        UserEntity u = dao.existsData(user);
        if (u != null) {
            if (u.getUserName().equals(user.getUserName())) {
                return Result.fail("当前登录名已被占用，请更改");
            } else if (u.getIdcard().equals(user.getIdcard())) {
                return Result.fail("身份证号码已存在");
            }
        }
        String s = "";
		try {
			s = AES2.Encrypt("123456", AES2.CODE);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail("密码转换异常："+e.getMessage());
		}
        user.setPassword(s);
        if (user.getId() == null) {
            dao.insert(user);
            return Result.success("添加成功");
        } else {
            dao.updateById(user);
            return Result.success("修改成功");
        }
    }

    /**
     * 登录
     * @return
     */
    public Result<?> selectLogin(UserEntity user) {
        try {
			user.setPassword(AesMin.aesDecrypt(user.getPassword()));// 前端解密
            String s = AES2.Encrypt(user.getPassword(), AES2.CODE);// 后端加密
            user.setPassword(s);
            user.setDelFlag(ConstantUtil.NOT_DEL);
            UserEntityResp login = dao.selectLogin(user);
            Integer loginFailCount = (Integer) session.getAttribute("loginFailCount");// 登录失败次数
            if (loginFailCount == null) { 
                session.setAttribute("loginFailCount", 0);
            }
            if (login != null) {
                if (MyDateUtil.getDateCount(null, login.getUseDate(), 2) < MyDateUtil.getDate().getTime()) {
                    return Result.fail("您的使用期限已过期");
                }
                if (login.getOrgState() == ConstantUtil.DISABLE) {
                    return Result.fail("当前项目已停用");
                }
                if (login.getRoleState() == ConstantUtil.DISABLE) {
                    return Result.fail("当前角色已停用");
                }
                LoginUser loginUser = new LoginUser();
                loginUser.setId(login.getId());
                loginUser.setName(login.getName());
                loginUser.setRid(login.getRid());
                loginUser.setSex(login.getSex());
                loginUser.setAge(login.getAge());
                loginUser.setRid(login.getRid());
                loginUser.setOid(login.getOid());
                loginUser.setOname(login.getOname());
                loginUser.setLastOid(login.getLastOid());
                loginUser.setLastOname(login.getLastOname());
                loginUser.setImg(login.getImg());
                loginUser.setTheme(login.getTheme());
                loginUser.setUserName(login.getUserName());
                session.setAttribute("loginUser", loginUser);
                String theme = StrUtil.isBlank(login.getTheme())?"theme1":login.getTheme();
                session.setAttribute("theme", theme);
                session.setAttribute("cache", login.getCache());
                session.setAttribute("themeStyle", login.getThemeStyle());
                String module = "module_theme0";
                if(StrUtil.isNotBlank(login.getThemeStyle())) {
                	if(login.getThemeStyle().indexOf("module1") != -1) {
                		module = "module_"+theme;
                	}
                }
                session.setAttribute("moduleTheme", module);
                session.setAttribute("loginFailCount", 0);
                session.setAttribute("suoPing", "ok");
                session.setMaxInactiveInterval(60*60);// 单位为秒 这里设置了一个钟（session存活时间）
                return Result.success("登录成功");
            } else {
            	loginFailCount = (Integer) session.getAttribute("loginFailCount");
            	loginFailCount ++;
                session.setAttribute("loginFailCount", loginFailCount);
                return Result.fail(loginFailCount, "登录失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.fail("系统异常："+e.getMessage());
        }
    }

    /**
     * 解锁
     * @return
     */
    public Result<?> suoPing(String mark, UserEntity user) {
        if (StrUtil.isEmpty(mark)) {
            session.setAttribute("suoPing", "");
            return Result.fail("锁屏中");
        }
        try {
        	user.setDelFlag(ConstantUtil.NOT_DEL);
        	user.setPassword(AesMin.aesDecrypt(user.getPassword()));// 前端解密
            String s = AES2.Encrypt(user.getPassword(), AES2.CODE);// 后端加密
            user.setPassword(s);
            UserEntityResp login = dao.selectLogin(user);
            if (login == null) {
            	return Result.fail("解锁失败");
            }
            session.setAttribute("suoPing", "ok");
            return Result.success("解锁成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return Result.fail("系统异常："+e.getMessage());
        }
    }


}
